package fina2.dcs.security.validators;

import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.naming.InitialContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

import fina2.dcs.context.ContextHelper;
import fina2.dcs.security.UserLocal;

@Name("userValidator")
@Scope(ScopeType.SESSION)
public class UserValidator implements Serializable{

	private ResourceBundle bundle;
	private InitialContext ic;
	private UserLocal ul;

	private String curPassword;

	private Log log = Logging.getLog(getClass());

	public UserValidator() {
		try {
			UIViewRoot ui = FacesContext.getCurrentInstance().getViewRoot();
			Locale l = ui.getLocale();
			ClassLoader cl = Thread.currentThread().getContextClassLoader();
			bundle = ResourceBundle.getBundle("messages", l, cl);
			ic = ContextHelper.getInitialContext();
			ul = ContextHelper.injectUserLocal(ic);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public void validateText(FacesContext fc, UIComponent ui, Object value) throws ValidatorException {
		String val = value.toString().trim();
		if ((val.length() < 1) || (val.length() > 255)) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Invalid Value");
			throw new ValidatorException(fm);
		}

	}

	public void validatePassword(FacesContext fc, UIComponent ui, Object value) throws ValidatorException {
		curPassword = value.toString().trim();
		System.out.println("Validating Password");
		if (curPassword.length() < 1) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Invalid Value");
			throw new ValidatorException(fm);
		}
		
	}

	public void validateConfirmPassword(FacesContext fc, UIComponent ui, Object value) throws ValidatorException {
		String val = value.toString().trim();
		System.out.println("Validating Confirm Password");
		if (val.length() < 1) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Confirmation is required");
			throw new ValidatorException(fm);
		}
		
		if (!ul.hashPassword(curPassword).trim().equals(ul.hashPassword(val))) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Confirmation Error");
			throw new ValidatorException(fm);
		}
	}
}
